package com.ruoyi.common.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;

/**
 * 通用http发送方法
 *
 * @author ruoyi
 */
public class HttpUtils
{
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url)
    {
        return sendGet(url, StringUtils.EMPTY);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param)
    {
        return sendGet(url, param, Constants.UTF8);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String contentType)
    {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setRequestProperty("Cookie","tc_TC=; _elane_shipfilter_type=%u8D27%u8239%2C%u96C6%u88C5%u7BB1%u8239%2C%u6CB9%u8F6E%2C%u5F15%u822A%u8239%2C%u62D6%u8F6E%2C%u62D6%u5F15%2C%u6E14%u8239%2C%u6355%u635E%2C%u5BA2%u8239%2C%u641C%u6551%u8239%2C%u6E2F%u53E3%u4F9B%u5E94%u8239%2C%u88C5%u6709%u9632%u6C61%u88C5%u7F6E%u548C%u8BBE%u5907%u7684%u8239%u8236%2C%u6267%u6CD5%u8247%2C%u5907%u7528-%u7528%u4E8E%u5F53%u5730%u8239%u8236%u7684%u4EFB%u52A1%u5206%u914D%2C%u5907%u7528-%u7528%u4E8E%u5F53%u5730%u8239%u8236%u7684%u4EFB%u52A1%u5206%u914D%2C%u533B%u7597%u8239%2C%u7B26%u540818%u53F7%u51B3%u8BAE%28Mob-83%29%u7684%u8239%u8236%2C%u62D6%u5F15%u5E76%u4E14%u8239%u957F%3E200m%u6216%u8239%u5BBD%3E25m%2C%u758F%u6D5A%u6216%u6C34%u4E0B%u4F5C%u4E1A%2C%u6F5C%u6C34%u4F5C%u4E1A%2C%u53C2%u4E0E%u519B%u4E8B%u884C%u52A8%2C%u5E06%u8239%u822A%u884C%2C%u5A31%u4E50%u8239%2C%u5730%u6548%u5E94%u8239%2C%u9AD8%u901F%u8239%2C%u5176%u4ED6%u7C7B%u578B%u7684%u8239%u8236%2C%u5176%u4ED6; _elane_shipfilter_length=0%2C40%2C41%2C80%2C81%2C120%2C121%2C160%2C161%2C240%2C241%2C320%2C321%2C9999; _elane_shipfilter_sog=0%2C1; _elane_shipfilter_olength=; tc_QX=; _9755xjdesxxd_=32; YD00803672648830%3AWM_NI=5sd01oxulqpj%2F8miSGCg0js6Cn4Ln8qQizEjFyZ%2BkobO7vQBn6th99b8CIOVC%2BvTh7bRRKU5Zc8I%2Bwk9tF0JI1LyQ%2FlcYGESsur%2FNZdXJ%2FswHRAdXndgMvyQsGVM1HbYdWo%3D; YD00803672648830%3AWM_NIKE=9ca17ae2e6ffcda170e2e6ee8bcd40bab5aedaf743f4968eb6c55a878e9eabaa3493bdb68dbc3e9a90afaeb22af0fea7c3b92af7adacd1b465bcaba492f362ede8a38ad24d81b9008bf23e81b2fcaded34b38fa79bc86286a796ccea65a291f997d44aaeeabc89bc33a2e88daace5e81f5bab5eb3da28e9eacd83f9abdf8aaaa7da9e7bca7b3428bef849ad425b0bd97a8c859b1abbed0cd52a88886d0f27d8c8e8f85db66a8b98397fc5bb1999aaeb444a287acb8ee37e2a3; YD00803672648830%3AWM_TID=vGtX10H2AT9EEREVBVM6pVJ3h9vZLKZy; gdxidpyhxdE=49%2BbnM7yXLd4nf%5Cq%5CccHckRUG%5ChdowiqXOj5eCqLO5SbRGK18EfNEXWBwVCmkt2Wb7oGICse%5CY%5Ce6hlsOR1XjS%2FDVtEb%5Cgbp7EAW1t%5CdiG5io81ipU7WgbJCmPvTN2X5mEYMbUCvkdQkw%2B1TTzgw8PG%5CkZvA%2FegvdRxz4lV7UdvANpUW%3A1632452927746; _filter_flag=-1; _elane_shipfilter_one=2; _elane_shipfilter_country=0%2C1%2C2; _elane_maptype=MT_GOOGLE; FD857C2AF68165D4=ROMgqVKA4P6WstBf0Vk+iwTjlequbnC3C29avdv58wb6459RdDdMtK/XQC/26xMA; .UserAuth2=D376D68AC03950F90058F181438BC710A1B6D2F40A049729A21138222E05CAC84C519A9341C7F3CF45CBAC9F87333C9FC88D519D1C42B41A2AF519DB2C394354F387055CC51876B301C384E62AD240BBA455ED93AEAAF83DF6B4A1CF3CD7A6347C929C33A08DA247206F0409B745BACF0327FDFC90126D008CA3EB8113146C267671CAD0; Hm_lvt_adc1d4b64be85a31d37dd5e88526cc47=1635814472,1635899677,1635991492,1636074683; _talent_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtfS1JMRk9TM1dPYk9ZcUN2ZEpKS2I3ZGo1TSIsImtpZCI6ImtfS1JMRk9TM1dPYk9ZcUN2ZEpKS2I3ZGo1TSJ9.eyJpc3MiOiJodHRwOi8vaWQyLmVsYW5lLmNvbS9jb3JlIiwiYXVkIjoiaHR0cDovL2lkMi5lbGFuZS5jb20vY29yZS9yZXNvdXJjZXMiLCJleHAiOjE2NDM4NTcyMTksIm5iZiI6MTYzNjA4MTIxOSwiY2xpZW50X2lkIjoiSFlRX1Jlc19BbGxJbiIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJ1c2VyYXBpIl0sInN1YiI6IjUxY2Q0Y2U3MGZiNGFkMzUiLCJhdXRoX3RpbWUiOjE2MzYwODEyMTksImlkcCI6Imlkc3J2IiwiYW1yIjpbInBhc3N3b3JkIl19.Qt6EKsxRORVa4-S-u8_GQy3Fl3Q797N8joIUsJjJqt-fuenoYd6hlJ3EA8MScFGZPLIf2UZqsA-16U1vQwI0jPRcdyzdXny0Tc1V26DfqEMxGC_HMnU3y_yS63fUDlKFzFe22ix01w2VrOeM-d7Uzpj_Z06ukA5P-_ntaqiiWn_L0BVZFT7wSCT0q69tjoZEm_mhjlDY_Gl4bbn4OJbHDBjnXpBfUlPflQJEh4OWmcR7Tm5C_BJMJnVj4AzOG8QnYScrPxFr75pHg6Jo7rRRHhAF25_UN5t8lnrjA3aFulL3GVotn43wk0hWKXiK8pRT5RSOmzBZ5EY3-QiZq8HBfA; Hm_lpvt_adc1d4b64be85a31d37dd5e88526cc47=1636093914; shipxy_v3_history_serch=s%u2606GERNER%20MAERSK%u2606220593000%u2606100%u2606IMO%uFF1A9359002%7Cs%u2606EVER%20LOYAL%u2606416495000%u2606100%u2606IMO%uFF1A9604158%7Cs%u2606EVER%20LOYAL%u26062079896%u260671%u2606IMO%uFF1A9604158%7Cs%u2606EVER%20LOYAL%u2606416494992%u260674%u2606MMSI%uFF1A416494992%7Cs%u2606MSC%20KALINA%u2606351361000%u2606100%u2606IMO%uFF1A9399026%7Cs%u2606MSC%20SAVONA%u2606636091959%u2606100%u2606IMO%uFF1A9460356%7Cs%u2606MSC%20KALINA%u2606351664660%u260671%u2606IMO%uFF1A9399026%7Cs%u2606SM%20NINGBO%u2606636019086%u2606100%u2606IMO%uFF1A9312937%7Cs%u2606SM%20MUMBAI%u2606636018097%u2606100%u2606IMO%uFF1A9401051%7Cs%u2606MING%20BIAO%20BO%202%u2606413330527%u260675%u2606MMSI%uFF1A413330527; SERVERID=6462d953552c3e70030b707fb585b257|1636094096|1636081218");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url, String param)
    {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try
        {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null)
            {
                if (ret != null && !"".equals(ret.trim()))
                {
                    result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();
    }

    private static class TrustAnyTrustManager implements X509TrustManager
    {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers()
        {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            return true;
        }
    }

    public static void main(String[] args) {
        String url = "http://www.shipxy.com/ship/GetShip";
        String param = "shipIDs=220593000&mmsi=220593000";
        String res;
        // 发送POST请求
        res = HttpUtils.sendPost(url, param);
        JSONObject jsobj = JSONObject.parseObject(res);
        JSONObject shipobj = (JSONObject)jsobj.getJSONArray("data").get(0);
        System.out.println(shipobj.get("lon"));
    }
}
